import axios from "axios";
import Element, { MessageBox } from "element-ui";
import store from "@/store";
import { getTokenDecrypt } from "@/utils/auth";
import { tansParams } from "@/utils/ruoyi";
import router from "@/router";
import { md5 } from "./aesUtils";
import qs from "qs";
axios.defaults.headers["Content-Type"] =
  // "application/x-www-form-urlencoded;charset=utf-8";
  "application/json;charset=utf-8";
let contentType = "application/x-www-form-urlencoded;charset=utf-8";
const urlForTips = ["/message/m/sysmsg/queryList", "/style/styleAvatar"];
const whiteList = ["/login/getLogout", "/system/bootstrap/asset/list"];

const handleTip = function (title, message, type = "error") {
  return new Promise((resolve, reject) => {
    MessageBox.confirm(message, title, {
      confirmButtonText: "确定",
      showCancelButton: false,
      type: type,
    })
      .then(() => {
        resolve();
      })
      .catch(() => {
        reject();
      });
  });
  // MessageBox.confirm(msg, title, {
  //   confirmButtonText: '确定',
  //   showCancelButton: false,
  //   type: type
  // }).then()
};

const AxiosConfig = {
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: window.sp_config.GLOBAL_REQUEST_TIMEOUT || 60 * 1000,
};

console.warn("接口超时时间: ", AxiosConfig.timeout / 1000, "秒");

// 创建axios实例
const service = axios.create(AxiosConfig);

let isError = false; // 控制所有异常信息提示只展示一次

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers["LoginVendor"] = md5(
      window.sp_config.CURRENT_THIRD_LOGIN_VENDOR
    ); //第三方登录/平台登录
    if (getTokenDecrypt()) {
      // config.headers["Authorization"] = "Bearer " + getTokenDecrypt(); // 让每个请求携带自定义token 请根据实际情况自行编辑
      config.headers["Authorization"] = getTokenDecrypt(); // 让每个请求携带自定义token 请根据实际情况自行编辑
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?";
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              let params = propName + "[" + key + "]";
              var subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (config.headers["Content-Type"] === contentType) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    console.log("Request拦截器异常: ", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // console.log(res)
    if (
      res &&
      res instanceof Object &&
      typeof res.data !== "string" &&
      res.data !== undefined
    ) {
      // 未设置状态码则默认成功状态
      const code = res.data.code || res.data.rescode || 200;
      // 获取错误信息
      // const msg = errorCode[code] || res.data.msg || errorCode['default']
      if (code === 200) {
        return res.data;
      } else if (code === 406) {
        if (getTokenDecrypt()) {
          MessageBox.confirm(res.data.msg, "系统提示", {
            confirmButtonText: "授权",
            cancelButtonText: "",
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
            type: "warning",
          }).then(() => {
            setTimeout(() => {
              router.push({
                path: "/unauthorized",
                query: { msg: res.data.msg },
              });
            }, 500);
          });
        }
        return { code: 200, data: null, rescode: 200, msg: null };
      } else if (code === 401) {
        MessageBox.confirm("登录状态已过期，请重新登录系统", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "",
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          type: "warning",
        }).then(() => {
          setTimeout(() => {
            store.dispatch("clearUserInfo").then(() => {
              location.href = "/";
            });
          }, 500);
        });
      } else {
        console.warn(res.data);
        return res.data;
      }
    } else {
      return Promise.reject({
        code: 500,
        rescode: 500,
        msg: "服务端没有响应!",
      });
    }
  },
  (error) => {
    console.log("response 拦截器 异常: ", error);
    let url = error.config.url;
    // 请求地址在白名单内，报错直接弹窗提示
    if (url && urlForTips.some((item) => url.includes(item))) {
      if (error.response) {
        // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        let { status, data } = error.response;
        let code = data && data.code ? data.code : status;
        if (code === 401) {
          MessageBox.confirm("登录状态已过期，请重新登录系统", "系统提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "",
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
            type: "warning",
          }).then(() => {
            setTimeout(() => {
              store.dispatch("clearUserInfo").then(() => {
                location.href = "/";
              });
            }, 500);
          });
        } else if (code === 403) {
          handleTip(
            "异常",
            data && data.msg ? data.msg : "请求接口403异常!"
          ).then();
        } else if (code === 404) {
          handleTip(
            "异常",
            data && data.msg ? data.msg : "请求接口404异常!"
          ).then();
        } else if (code === 406) {
          if (getTokenDecrypt()) {
            router.push({
              path: "/unauthorized",
              query: { msg: data.msg },
            });
          }
        } else {
          // handleTip(
          //   "异常",
          //   data && data.msg ? data.msg : "未知异常!,请联系管理员!"
          // ).then();
        }
      } else if (error.request) {
        handleTip("异常", "服务未响应!").then();
      } else {
        // 发送请求时出了点问题
        handleTip("异常", "网络异常!").then();
      }
    } else if (url && whiteList.some((item) => url.includes(item))) {
    } else if (!isError) {
      // isError用于限制页面中请求报错弹窗弹出次数
      isError = true;
      if (error.response) {
        // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        let { status, data } = error.response;
        let code = data && data.code ? data.code : status;

        if (code === 401) {
          MessageBox.confirm("登录状态已过期，请重新登录系统", "系统提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "",
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
            type: "warning",
          })
            .then(() => {
              setTimeout(() => {
                isError = false;
                store.dispatch("clearUserInfo").then(() => {
                  location.href = "/";
                });
              }, 500);
            })
            .finally(() => {
              isError = false;
            });
        } else if (code === 403) {
          handleTip(
            "异常",
            data && data.msg ? data.msg : "请求接口403异常!"
          ).finally(() => (isError = false));
        } else if (code === 404) {
          // handleTip(
          //   "异常",
          //   data && data.msg ? data.msg : "请求接口404异常!"
          // ).finally(() => (isError = false));
        } else if (code === 406) {
          if (getTokenDecrypt()) {
            router.push({
              path: "/unauthorized",
              query: { msg: data.msg },
            });
          }
        } else {
          // handleTip(
          //   "异常",
          //   data && data.msg ? data.msg : "未知异常!,请联系管理员!"
          // ).finally(() => (isError = false));
        }
      } else if (error.request) {
        handleTip("异常", "服务未响应!").finally(() => (isError = false));
        /* MessageBox.confirm('登录状态已过期，请重新登录系统', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '',
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          type: 'warning'
        }).then(() => {
          setTimeout(() => {
            isError = false
            store.dispatch('clearUserInfo').then(() => {
              location.href = '/'
            })
          }, 500)
        }).finally(() => {
          isError = false
        })*/
      } else {
        // 发送请求时出了点问题
        handleTip("异常", "网络异常!").finally(() => (isError = false));
      }
    }
  }
);

// 通用下载方法
export function download(url, params, filename, timeout = 30000) {
  if (url.indexOf("/") !== 0) url = `/${url}`;
  return service
    .post(url, params, {
      timeout,
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      responseType: "blob",
    })
    .then((data) => {
      const content = data;
      const blob = new Blob([content]);
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = filename;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, filename);
      }
    })
    .catch((r) => {
      console.error(r);
    });
}

export default service;
